package cn.wolfcode.trip.admin.controller;


import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.query.TravelCommendQueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;


@Controller
@RequestMapping("travelCommend")
public class TravelCommendController {
    @Autowired
    private ITravelCommendService travelCommendService;

    @Autowired
    ServletContext servletContext;


    @RequestMapping("list")
    public  String list(Model model, @ModelAttribute("qo") TravelCommendQueryObject qo){
        //按照推荐时间倒序
        qo.setOrderBy("tc.schedule desc");
        model.addAttribute("result",travelCommendService.queryForlist(qo));
        return "travel/commend";
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(MultipartFile file,TravelCommend travelCommend){
        JSONResult result = new JSONResult();
        try {
            //如果有上传图片才设置
            if (file!=null&&file.getSize()>0){
                String imgUrl = UploadUtil.upload(file,servletContext.getRealPath("/upload"));
                travelCommend.setCoverUrl(imgUrl);
            }

            if (travelCommend.getId()!=null){
                travelCommendService.update(travelCommend);
            }else {
                travelCommendService.save(travelCommend);
            }
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }


}

